﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;

namespace WinTime.Helpers;
public class SelfRunHelper
{

    /// <summary>
    /// 设置开机启动
    /// </summary>
    /// <param name="selfRun"></param>
    /// <returns></returns>
    public static bool SetSelfRun(bool selfRun = true)
    {
        var selfRunRigistryPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
        //获取要自动运行的应用程序名
        var appPath = AppDomain.CurrentDomain.BaseDirectory + "WinTime.exe";
        if (!File.Exists(appPath))
        {
            return false;
        }
        //获取应用程序文件名，不包括路径
        var strnewName = "KnifeZ.WinTime";
        RegistryKey registry = Registry.CurrentUser.OpenSubKey(selfRunRigistryPath, true);
        if (selfRun)
        {
            #region 设置开机自启
            //若指定的子项不存在
            if (registry == null)
            {
                //则创建指定的子项
                registry = Registry.CurrentUser.CreateSubKey(selfRunRigistryPath);

            }
            //设置该子项的新的“键值对”
            registry.SetValue(strnewName, appPath, RegistryValueKind.String);
            #endregion
        }
        else
        {
            //删除指定“键名称”的键/值对
            registry?.DeleteValue(strnewName, false);
        }
        return true;
    }
}
